//
//  ZJBaseViewController.m
//  zijinlian
//
//  Created by lzy on 2017/3/6.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "ZJBaseViewController.h"
#import "ZJBaseAFManager.h"
#import "EaseMessageViewController.h"
@interface ZJBaseViewController ()

@end

@implementation ZJBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isShowDiag=YES;
    self.view.backgroundColor=RGB(246, 246, 246);
    [self createView];
    [self doOpeartion];
    [self doRequest];
    [self showNav];
    [self showShadowView];
	
//		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

}
-(void)exditView{
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
}
//键盘收起
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    [self.view endEditing:YES];
    
}
//标题设置
-(void)initTitle:(NSString*)title{
    self.title=title;
}

//子类重写
-(void)doOpeartion{


}
//子类重写
-(void)createView{


}
//子类重写
-(void)doRequest{


}
-(void)creatNavUI{
    
}
-(void)showShadow{
    [self.view addSubview:self.shadowView];
}
-(void)disShadow{
    [self.shadowView removeFromSuperview];
}
-(void)showShadowView{
    self.shadowView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH)];
    self.shadowView.backgroundColor=[UIColor blackColor];
    self.shadowView.alpha=0.3;
}
-(void)showNav{
    self.navigationController.navigationBar.hidden=NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"image_nav"] forBarMetrics:UIBarMetricsDefault];
}
//做网络请求
-(void)doHttpRequestWithApi:(NSString*)api method:(HTTPMethod)method dic:(NSMutableDictionary*)dic successBlock:(requestSuccessBlock)block {
    if (self.isShowDiag==YES) {
        [self showDialog];
    }
    
   [[ZJBaseAFManager sharedManager] requestHttpWithMethod:method withPath:api withDictionary:dic withSuccessBlock:^(NSDictionary *dic) {
//	   if (self.isShowDiag==YES) {
		   [self dismissDialog];
//	   }
       block(dic);
   } withFinishBlock:^{
//       if (self.isShowDiag==YES) {
           [self dismissDialog];
//       }
	   
   } ];
}


//网络请求的菊花

-(void)showDialog{
    if (_hud==nil) {
        _hud = [MBProgressHUD showHUDAddedTo:[UIApplication alloc].keyWindow animated:YES];
        _hud.mode = MBProgressHUDModeCustomView;
    }
    UIImageView* view =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_loading"]];
    view.frame=CGRectMake(0, 0, 60, 60);
    CABasicAnimation *anima = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anima.toValue = @(M_PI*2);
    anima.duration = 1;
    anima.repeatCount = MAXFLOAT;
    [view.layer addAnimation:anima forKey:nil];
    _hud.customView=view;
    _hud.labelText=MyString(@"加载中");
    _hud.minSize=CGSizeMake(MainW, MainH*2);
    _hud.yOffset=-0;
//    if (_hud.hidden==NO) {
//        [_hud hide:YES afterDelay:1];
//    }
	
}

-(void)showLoad
{
	MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	_hud = HUD;
	[self.navigationController.view addSubview:_hud];
	_hud.delegate = (id)self;
	_hud.labelText = @"";
	[_hud show:YES];
}
-(void)hidLoad
{
	_hud.hidden = YES;
}






-(void)dismissDialog{
    [_hud hide:YES];
}

-(void)showToast:(NSString*)msg{
   _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.mode=MBProgressHUDModeText;
    _hud.labelText=msg;
    _hud.dimBackground=NO;
    [_hud hide:YES afterDelay:2];
    
}


//提示弹框
-(void)showMessage:(NSString *)info{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:info delegate:nil cancelButtonTitle:MyString(@"确定") otherButtonTitles:nil, nil];
    [alert show];
    
}

//键盘的处理
-(void)doKeyBoardDown{
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped)];
    [self.view addGestureRecognizer:singleTap];
}

-(void)fingerTapped{
    [self.view endEditing:YES];
}
-(void)saveImage:(UIImageView *)imag{
    //1.创建长按手势
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick:)];
    
    //2.开启人机交互
    imag.userInteractionEnabled = YES;
    
    //3.添加手势
    [imag addGestureRecognizer:longTap];
}
#pragma mark 长按手势弹出警告视图确认
-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture

{
    
    if(gesture.state==UIGestureRecognizerStateBegan)
        
    {
        
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:MyString(@"保存图片") message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:MyString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"取消保存图片");
        }];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:MyString(@"确认") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"确认保存图片");
            
            // 保存图片到相册
            UIImageWriteToSavedPhotosAlbum(self.saveImg.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
            
            //            UIImageWriteToSavedPhotosAlbum(<#UIImage * _Nonnull image#>, <#id  _Nullable completionTarget#>, <#SEL  _Nullable completionSelector#>, <#void * _Nullable contextInfo#>)
            
        }];
        
        [alertControl addAction:cancel];
        [alertControl addAction:confirm];
        
        [self presentViewController:alertControl animated:YES completion:nil];
        
    }
    
}

#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo

{
    
    NSString*message =@"呵呵";
    
    if(!error) {
        
        message =MyString(@"成功保存到相册");
        
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:MyString(@"提示") message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:MyString(@"确定") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertControl addAction:action];
        
        [self presentViewController:alertControl animated:YES completion:nil];
        
    }else
        
    {
        
        message = [error description];
        
        
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:MyString(@"提示") message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:MyString(@"确定") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertControl addAction:action];
        
        [self presentViewController:alertControl animated:YES completion:nil];
        
    }
    
}
//联系客服

//延迟几秒回上个页面
-(void)popToLastController:(CGFloat)time{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
    
}
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
- (BOOL) deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}
-(void)showTempView:(NSString *)title Image:(NSString *)imageName CGFrame:(CGRect)frame{
    self.tempView=[[UIView alloc]initWithFrame:frame];
    self.tempView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.tempView];
    UIImageView*image=[[UIImageView alloc]initWithFrame:CGRectMake(MainW/2-65, MainH/10, 130, 150)];
    image.image=[UIImage imageNamed:imageName];
    [self.tempView addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(150);
        make.width.mas_equalTo(130);
        make.centerX.mas_equalTo(self.tempView.mas_centerX);
        make.centerY.mas_equalTo(self.tempView.mas_centerY).mas_offset(-50);
    }];
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0, MainH/10+150+15, MainW, 30)];
    label.text=title;
    label.textColor=TextColor6;
    label.textAlignment=1;
    label.font=FontAndStyle14;
    [self.tempView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(image.mas_bottom).mas_offset(10);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(MainW);
    }];
    //return self.tempView;
}
-(void)showWishTempView:(NSString *)title Image:(NSString *)imageName CGFrame:(CGRect)frame{
    self.tempView=[[UIView alloc]initWithFrame:frame];
    self.tempView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.tempView];
    UIImageView*image=[[UIImageView alloc]initWithFrame:CGRectMake(0, MainH/10, MainW, MainW*2/3)];
    image.image=[UIImage imageNamed:imageName];
    [self.tempView addSubview:image];
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0, MainH/10+150+15, MainW, 30)];
    label.text=title;
    label.textColor=TextColor6;
    label.textAlignment=1;
    label.font=FontAndStyle14;
    [self.tempView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(image.mas_bottom).mas_offset(10);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(MainW);
    }];
}
- (NSAttributedString*)messageAction:(UILabel *)theLab changeString:(NSString *)change andAllColor:(UIColor *)allColor andMarkColor:(UIColor *)markColor andMarkFondSize:(float)fontSize {
    NSString *tempStr = theLab.text;
    NSMutableAttributedString *strAtt = [[NSMutableAttributedString alloc] initWithString:tempStr];
    [strAtt addAttribute:NSForegroundColorAttributeName value:allColor range:NSMakeRange(0, [strAtt length])];
    NSRange markRange = [tempStr rangeOfString:change];
    [strAtt addAttribute:NSForegroundColorAttributeName value:markColor range:markRange];
    [strAtt addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue" size:fontSize] range:markRange];
    theLab.attributedText = strAtt;
    return theLab.attributedText;
}
- (BOOL) isEmpty:(NSString *) str {
    if (!str) {
        return YES;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return YES;
        } else {
            return NO;
        }
    }
}
@end
